<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bou Scheduler - 延迟任务调度器</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .stat-card {
            transition: transform 0.2s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .status-running {
            color: #28a745;
        }
        .status-stopped {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-clock-history"></i> Bou Scheduler
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/"><i class="bi bi-house"></i> 首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/tasks"><i class="bi bi-list-task"></i> 任务管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/monitor"><i class="bi bi-graph-up"></i> 监控统计</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/settings"><i class="bi bi-gear"></i> 系统设置</a>
                    </li>
                </ul>
                <span class="navbar-text">
                    <i class="bi bi-person-circle"></i> 管理员
                </span>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <!-- 页面标题 -->
        <div class="row mb-4">
            <div class="col">
                <h1><i class="bi bi-speedometer2"></i> 系统仪表板</h1>
                <p class="text-muted">延迟任务调度器运行状态概览</p>
            </div>
        </div>

        <!-- 系统状态 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-info-circle"></i> 系统状态</h5>
                        <div class="d-flex align-items-center">
                            <span class="me-3">调度器状态:</span>
                            <span th:if="${isRunning}" class="badge bg-success fs-6">
                                <i class="bi bi-play-circle"></i> 运行中
                            </span>
                            <span th:unless="${isRunning}" class="badge bg-danger fs-6">
                                <i class="bi bi-stop-circle"></i> 已停止
                            </span>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted">运行时长: <span th:text="${#numbers.formatDecimal(statistics.uptime / 1000, 1, 2)}">0</span> 秒</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-clock"></i> 性能指标</h5>
                        <div class="row">
                            <div class="col-6">
                                <div class="text-center">
                                    <h4 class="text-primary" th:text="${#numbers.formatDecimal(statistics.tasksPerSecond, 1, 2)}">0</h4>
                                    <small class="text-muted">任务/秒</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="text-center">
                                    <h4 class="text-success" th:text="${#numbers.formatDecimal(statistics.successRate, 1, 1)}">0</h4>
                                    <small class="text-muted">成功率 %</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stat-card bg-primary text-white">
                    <div class="card-body text-center">
                        <i class="bi bi-list-ul fs-1"></i>
                        <h3 class="mt-2" th:text="${statistics.totalTasks}">0</h3>
                        <p class="mb-0">总任务数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card bg-warning text-white">
                    <div class="card-body text-center">
                        <i class="bi bi-hourglass-split fs-1"></i>
                        <h3 class="mt-2" th:text="${statistics.pendingTasks}">0</h3>
                        <p class="mb-0">待执行任务</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card bg-info text-white">
                    <div class="card-body text-center">
                        <i class="bi bi-play-circle fs-1"></i>
                        <h3 class="mt-2" th:text="${statistics.runningTasks}">0</h3>
                        <p class="mb-0">执行中任务</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card bg-success text-white">
                    <div class="card-body text-center">
                        <i class="bi bi-check-circle fs-1"></i>
                        <h3 class="mt-2" th:text="${statistics.successTasks}">0</h3>
                        <p class="mb-0">成功任务</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 快速操作 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-lightning"></i> 快速操作</h5>
                        <div class="d-grid gap-2">
                            <button th:if="${!isRunning}" class="btn btn-success" onclick="startScheduler()">
                                <i class="bi bi-play-circle"></i> 启动调度器
                            </button>
                            <button th:if="${isRunning}" class="btn btn-danger" onclick="stopScheduler()">
                                <i class="bi bi-stop-circle"></i> 停止调度器
                            </button>
                            <a href="/tasks" class="btn btn-primary">
                                <i class="bi bi-plus-circle"></i> 创建新任务
                            </a>
                            <button class="btn btn-warning" onclick="cleanupCompletedTasks()">
                                <i class="bi bi-trash"></i> 清理已完成任务
                            </button>
                            <button class="btn btn-info" onclick="resetStatistics()">
                                <i class="bi bi-arrow-clockwise"></i> 重置统计信息
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-graph-up"></i> 实时监控</h5>
                        <p class="card-text">查看详细的性能指标和任务执行情况</p>
                        <a href="/monitor" class="btn btn-outline-primary">
                            <i class="bi bi-arrow-right"></i> 查看详情
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近任务 -->
        <div class="row">
            <div class="col">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-clock-history"></i> 最近任务</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>任务ID</th>
                                        <th>任务名称</th>
                                        <th>类型</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="recentTasksTable">
                                    <tr>
                                        <td colspan="6" class="text-center text-muted">
                                            <i class="bi bi-inbox"></i> 暂无任务数据
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-light mt-5 py-3">
        <div class="container text-center">
            <span class="text-muted">© 2024 Bou Scheduler. 基于Redis和Netty时间轮算法的延迟任务调度框架</span>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/js/utils.js"></script>
    <script>
        // 启动调度器
        function startScheduler() {
            const btn = event.target;
            const originalText = btn.innerHTML;
            
            // 显示加载状态
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> 启动中...';
            
            fetch('/api/tasks/scheduler/start', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('调度器启动成功！');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showError('启动失败: ' + data.message);
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('启动失败，请检查网络连接');
                btn.disabled = false;
                btn.innerHTML = originalText;
            });
        }

        // 停止调度器
        function stopScheduler() {
            const btn = event.target;
            const originalText = btn.innerHTML;
            
            // 显示加载状态
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> 停止中...';
            
            fetch('/api/tasks/scheduler/stop', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('调度器停止成功！');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showError('停止失败: ' + data.message);
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError('停止失败，请检查网络连接');
                btn.disabled = false;
                btn.innerHTML = originalText;
            });
        }

        // 清理已完成任务
        function cleanupCompletedTasks() {
            // 使用通用清理函数，清理1小时前的任务
            if (typeof window.globalCleanupCompletedTasks === 'function') {
                window.globalCleanupCompletedTasks(1, function(data) {
                    // 成功回调：延迟刷新页面
                    setTimeout(() => location.reload(), 1000);
                }, function(errorMessage) {
                    // 错误回调：恢复按钮状态
                    const btn = event.target;
                    btn.disabled = false;
                    btn.innerHTML = '<i class="bi bi-trash"></i> 清理已完成任务';
                });
            } else {
                // 如果通用函数不可用，使用备用实现
                cleanupCompletedTasksLocal();
            }
        }

        // 本地清理任务实现（避免递归调用）
        function cleanupCompletedTasksLocal() {
            if (confirm('确定要清理所有已完成任务吗？这将删除所有已成功、失败或已取消的任务。')) {
                const btn = event.target;
                const originalText = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-hourglass-split"></i> 清理中...';

                // 设置清理时间为1小时前，使用本地时间
                const now = new Date();
                const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
                
                // 格式化为 YYYY-MM-DDTHH:mm:ss 格式，使用本地时间
                const year = oneHourAgo.getFullYear();
                const month = String(oneHourAgo.getMonth() + 1).padStart(2, '0');
                const day = String(oneHourAgo.getDate()).padStart(2, '0');
                const hours = String(oneHourAgo.getHours()).padStart(2, '0');
                const minutes = String(oneHourAgo.getMinutes()).padStart(2, '0');
                const seconds = String(oneHourAgo.getSeconds()).padStart(2, '0');
                
                const beforeTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;

                fetch(`/api/tasks/cleanup?beforeTime=${beforeTime}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess(`已完成任务清理成功！共清理 ${data.data} 个任务`);
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showError('清理失败: ' + data.message);
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('清理失败，请检查网络连接');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
            }
        }

        // 重置统计信息
        function resetStatistics() {
            if (confirm('确定要重置所有统计信息吗？这将清除所有性能指标和任务计数。')) {
                const btn = event.target;
                const originalText = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '<i class="bi bi-hourglass-split"></i> 重置中...';

                fetch('/api/tasks/scheduler/statistics/reset', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess('统计信息重置成功！');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showError('重置失败: ' + data.message);
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('重置失败，请检查网络连接');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
            }
        }

        // 加载最近任务
        function loadRecentTasks() {
            fetch('/api/tasks?size=5')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data && data.data.length > 0) {
                    const tbody = document.getElementById('recentTasksTable');
                    tbody.innerHTML = '';
                    
                    data.data.forEach(task => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td><code>${task.taskId.substring(0, 8)}...</code></td>
                            <td>${task.taskName}</td>
                            <td><span class="badge bg-secondary">${task.taskType}</span></td>
                            <td>${getStatusBadge(task.status)}</td>
                            <td>${formatDateTime(task.createTime)}</td>
                            <td>
                                <a href="/tasks?id=${task.taskId}" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-eye"></i>
                                </a>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                } else {
                    const tbody = document.getElementById('recentTasksTable');
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="6" class="text-center text-muted">
                                <i class="bi bi-inbox"></i> 暂无任务数据
                            </td>
                        </tr>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading recent tasks:', error);
                const tbody = document.getElementById('recentTasksTable');
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center text-danger">
                            <i class="bi bi-exclamation-triangle"></i> 加载失败
                        </td>
                    </tr>
                `;
            });
        }

        // 获取状态徽章
        function getStatusBadge(status) {
            const statusMap = {
                'PENDING': { class: 'bg-warning', text: '待执行' },
                'RUNNING': { class: 'bg-info', text: '执行中' },
                'SUCCESS': { class: 'bg-success', text: '成功' },
                'FAILED': { class: 'bg-danger', text: '失败' },
                'CANCELLED': { class: 'bg-secondary', text: '已取消' },
                'RETRYING': { class: 'bg-warning', text: '重试中' },
                'TIMEOUT': { class: 'bg-danger', text: '超时' }
            };
            const statusInfo = statusMap[status] || { class: 'bg-secondary', text: status };
            return `<span class="badge ${statusInfo.class}">${statusInfo.text}</span>`;
        }

        // 获取优先级徽章
        function getPriorityBadge(priority) {
            const priorityMap = {
                0: { class: 'bg-primary', text: '普通' },
                1: { class: 'bg-warning', text: '高' },
                2: { class: 'bg-danger', text: '紧急' },
                3: { class: 'bg-secondary', text: '低' }
            };
            const priorityInfo = priorityMap[priority] || { class: 'bg-secondary', text: '未知' };
            return `<span class="badge ${priorityInfo.class}">${priorityInfo.text}</span>`;
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '-';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN');
        }

        // 实时更新系统状态
        function updateSystemStatus() {
            fetch('/api/tasks/scheduler/status')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const status = data.data;
                    const statusBadge = document.querySelector('.badge');
                    if (status === 'RUNNING') {
                        statusBadge.className = 'badge bg-success fs-6';
                        statusBadge.innerHTML = '<i class="bi bi-play-circle"></i> 运行中';
                    } else {
                        statusBadge.className = 'badge bg-danger fs-6';
                        statusBadge.innerHTML = '<i class="bi bi-stop-circle"></i> 已停止';
                    }
                }
            })
            .catch(error => {
                console.error('Error updating system status:', error);
            });
        }

        // 更新任务统计卡片
        function updateTaskStats() {
            fetch('/api/tasks')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const tasks = data.data;
                    const totalTasks = tasks.length;
                    const pendingTasks = tasks.filter(t => t.status === 'PENDING').length;
                    const runningTasks = tasks.filter(t => t.status === 'RUNNING').length;
                    const successTasks = tasks.filter(t => t.status === 'SUCCESS').length;
                    
                    // 更新统计卡片
                    document.getElementById('totalTasks').textContent = totalTasks;
                    document.getElementById('pendingTasks').textContent = pendingTasks;
                    document.getElementById('runningTasks').textContent = runningTasks;
                    document.getElementById('successTasks').textContent = successTasks;
                    
                    console.log('统计更新:', {
                        total: totalTasks,
                        pending: pendingTasks,
                        running: runningTasks,
                        success: successTasks
                    });
                }
            })
            .catch(error => {
                console.error('Error updating task stats:', error);
            });
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            loadRecentTasks();
            updateSystemStatus();
            updateTaskStats(); // 添加统计卡片更新
            
            // 每30秒刷新一次数据
            setInterval(() => {
                loadRecentTasks();
                updateSystemStatus();
                updateTaskStats(); // 添加统计卡片更新
            }, 30000);
        });
    </script>
</body>
</html>
